home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / DJLSR106.ARJ / STRTOUL.CC < prev    next >
C/C++ Source or Header  |  1992-03-29  |  2KB  |  92 lines

  1. /* Lightly hacked and C++-ified from the Berkeley C l;ibrary. */
  2.  
  3. /*
  4.  * strtoul : convert a string to long.
  5.  *
  6.  * Andy Wilson, 2-Oct-89.
  7.  */
  8.  
  9. #include <errno.h>
  10. #include <ctype.h>
  11. #include <stdio.h>
  12. /*#include "ansidecl.h"*/
  13.  
  14. #define    ULONG_MAX    ((unsigned long)(~0L))        /* 0xFFFFFFFF */
  15.  
  16. extern int errno;
  17.  
  18. extern "C" unsigned long
  19. strtoul(const char *s, char **ptr, int base)
  20. {
  21.   unsigned long total = 0, tmp = 0;
  22.   int digit;
  23.   const char *start=s;
  24.   int did_conversion=0;
  25.   int negate = 0;
  26.  
  27.   if (s==NULL)
  28.     {
  29.       errno = ERANGE;
  30.       if (!ptr)
  31.     *ptr = (char *)start;
  32.       return 0L;
  33.     }
  34.  
  35.   while (isspace(*s))
  36.     s++;
  37.   if (*s == '+')
  38.     s++;
  39.   else if (*s == '-')
  40.     s++, negate = 1;
  41.   if (base==0)
  42.     {
  43.       /*
  44.        * try to infer base from the string
  45.        * (assume decimal).
  46.        */
  47.       base = 10;
  48.       if (*s=='0')
  49.     {
  50.       base = 8;    /* guess it's octal */
  51.       s++;        /* (but check for hex) */
  52.       if (*s=='X' || *s=='x')
  53.         {
  54.           s++;
  55.           base = 16;
  56.         }
  57.     }
  58.     }
  59.  
  60.   while ( digit = *s )
  61.     {
  62.       if (digit >= '0' && digit < ('0'+base))
  63.     digit -= '0';
  64.       else
  65.     if (base > 10)
  66.       {
  67.         if (digit >= 'a' && digit < ('a'+base))
  68.           digit = digit - 'a' + 10;
  69.         else if (digit >= 'A' && digit < ('A'+base))
  70.           digit = digit - 'A' + 10;
  71.         else
  72.           break;
  73.       }
  74.     else
  75.       break;
  76.       did_conversion = 1;
  77.       tmp = (total * base) + digit;
  78.       if (tmp < total)    /* check overflow */
  79.     {
  80.       errno = ERANGE;
  81.       if (ptr != NULL)
  82.         *ptr = (char *)s;
  83.       return (ULONG_MAX);
  84.     }
  85.       total = tmp;
  86.       s++;
  87.     }
  88.   if (ptr != NULL)
  89.     *ptr = (char *) ((did_conversion) ? (char *)s : start);
  90.   return negate ? -total : total;
  91. }
  92.